<?php
namespace Crawl\Controller;
use Common\Controller\AdminbaseController;
use Think\Cache\Driver\Redis;

class KeywordController extends AdminbaseController{
	protected $model;
	protected $redis_key;
	public function _initialize(){
		$this->model = M('CrawlKeyword');
		$this->redis_key = C('REDIS_PREFIX')."keyword";
	}
	
	
	public function index(){
	    $list = $this->lists($this->model);
	    $this->assign('list',$list);
	    $this->display();
	}
	
	public function flush(){
	    $oldkey = $this->model->getField('key',true);
	    $redis = new Redis();
	    $redis->ltrim($this->redis_key,1,0);
	    foreach ($oldkey as $v){
    	    $redis->lPush($this->redis_key,$v);
	    }
	    $this->success('缓存更新完成！~');
	}
	
	
	/**
	 * 编辑
	 *
	 * date:2016年11月22日
	 * author: EK_熊
	 */
	public function edit(){
	    $id = I('id');
	    $pk = $this->model->getPk();
	    if (IS_POST){
	        $redis = new Redis();
	        $post = I('post');
	        $post['updated_time'] =CURRENT_TIME;
	        $where[$pk] = $id;
	        $oldkey = $this->model->where($where)->getField('key');
	        $ret = $this->model->where($where)->save($post);
	        if (!$ret) $this->error('操作失败！');
	        
            $redis->lRem($this->redis_key,$oldkey,0);
            $redis->lPush($this->redis_key,$post['key']);
	        
	        $this->success('操作成功！');
	    }
	    $info = $this->model->where([$pk=>$id])->find();
	    $this->assign('status',$this->status);
	    $this->assign('info',$info);
	    $this->display();
	}
	
	/**
	 * 新增
	 *
	 * date:2016年11月22日
	 * author: EK_熊
	 */
	public function add(){
	    
	    if (IS_POST) {
	        $post = I('post');
	        $post['updated_time'] =CURRENT_TIME;
	        
	        $exist = $this->model->where(['key'=>$post['key']])->find();
	        if ($exist) $this->error('该关键词已经存在');
	        
	        $ret = $this->model->add($post);
	        if (!$ret) $this->error('添加失败！');
	        
	        $redis = new Redis();
	        $ret_redis = $redis->lPush($this->redis_key,$post['key']);
	        
	        $this->success('添加成功！');
	    }
	
	    $this->assign('status',$this->status);
	    $this->display();
	}
	
	/**
	 * 删除数据,可批量
	 * @param unknown $model
	 * date:2016年11月22日
	 * author: EK_熊
	 */
	public function delete($model=''){
	    $model = $this->model;
	    $ids = I('ids');
	    $pk = $model->getPk();
	    $map[$pk] = array('in',$ids);
	    
	    $findret = $model->where($map)->getField('key',true);
	    
	    $ret = $model->where($map)->delete();
	    if (!$ret) $this->error('操作失败,网络异常！');
	    
	    $redis = new Redis();
	    foreach ($findret as $v) {
    	    $ret_redis = $redis->lRem($this->redis_key,$v);
	    }
	    
	    $this->success('操作成功！');
	}
	
}